<template>
	<el-drawer v-model="dialogVisible" :title="formText" :destroy-on-close="true" direction="rtl" size="80%">
		<el-card style="width: 100%" v-loading="loading">
			<template #header>
				<div class="card-header">
					<span>基础信息 </span>
				</div>
			</template>
			<el-form ref="dataFormRef" v-if="['act_add'].includes(dialogStatus)" :model="formTemp" :rules="cRules"
				label-width="120px">
				<el-row :gutter="12">
					<el-col :span="7">
						<el-form-item label="所属公司" prop="cid">
							<el-tree-select :disabled="formTemp.goods?.length >0" style="width: 100%;"
								placeholder="请选择所属公司" v-model="formTemp.cid" :data="baseConfigStore.newExCompanyList"
								:render-after-expand="false" :default-expand-all="true" check-strictly clearable
								@node-click="nodeClickCompany" @clear="nodeClearCompany">
								<template v-slot:default="{node, data }">
									<treeBlock :nodeItem="node" :dataItem="data" :typeClass="0"></treeBlock>
								</template>
							</el-tree-select>
						</el-form-item>
					</el-col>
					<el-col :span="7">
						<el-form-item label="仓库" prop="sid">
							<el-select :disabled="formTemp.goods?.length >0" v-model="formTemp.sid" placeholder="请选择仓库"
								clearable>
								<el-option v-for="item in stockList" :key="item.id" :label="item.name"
									:value="item.id" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="7">
						<el-form-item label="批次号" prop="batch_no">
							<el-input v-model="formTemp.batch_no" placeholder="请输入批次号" clearable />
						</el-form-item>
					</el-col>
				</el-row>
				<el-row :gutter="12">
					<el-col :span="7">
						<el-form-item label="出库时间" prop="outbound_time">
							<el-date-picker style="width: 100%;" v-model="formTemp.outbound_time" placeholder="请输选择入库时间"
								clearable value-format="YYYY-MM-DD" type="date" />
						</el-form-item>
					</el-col>
				</el-row>
				<el-row :gutter="12">
					<el-col :span="21">
						<el-form-item label="备注信息" prop="mark">
							<el-input v-model="formTemp.mark" placeholder="请输入备注信息" maxlength="200" show-word-limit
								rows="5" resize="none" type="textarea" />
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<div  v-if="['act_info'].includes(dialogStatus)">
				<el-row :gutter="12">
					<el-col :span="7">
						<el-form-item label="所属公司:">
							{{formTemp.company?.name}}
						</el-form-item>
					</el-col>
					<el-col :span="7">
						<el-form-item label="仓库:">
							{{formTemp.stockroom?.name}}
						</el-form-item>
					</el-col>
					<el-col :span="7">
						<el-form-item label="批次号:">
							{{formTemp.batch_no}}
						</el-form-item>
					</el-col>
				</el-row>
				<el-row :gutter="12">
					<el-col :span="7">
						<el-form-item label="出库时间:">
							{{formTemp.outbound_time}}
						</el-form-item>
					</el-col>
				</el-row>
				<el-row :gutter="12">
					<el-col :span="21">
						<el-form-item label="备注信息:" prop="mark">
							{{formTemp.mark || '无'}}
						</el-form-item>
					</el-col>
				</el-row>
			</div>
		</el-card>
		<el-card style="width: 100%;margin-top: 20px;" v-loading="loading">
			<template #header>
				<div class="card-header">
					<span>物品信息 </span>
				</div>
			</template>
			<div class="action-row" v-if="['act_add'].includes(dialogStatus)">
				<el-button @click="handleAdd()" :disabled="!formTemp.sid" :type="buttonType(formTemp.sid?1:0)"
					plain><template #icon><i-ep-plus /></template>添加</el-button>
				<el-button @click="handleDelete()" :disabled="multipleSelection.length == 0"
					:type="buttonType(multipleSelection.length > 0 ?1:0)" plain><template
						#icon><i-ep-delete /></template>删除</el-button>
				<el-button @click="handleSubmit()" :disabled="formTemp.goods?.length == 0"
					:type="buttonType(formTemp.goods?.length > 0 ?1:0)" plain><template
						#icon><i-ep-finished /></template>保存</el-button>
			</div>
			<el-table ref="dataTableRef" v-loading="loading" :data="formTemp.goods" align="left" tooltip-effect="dark"
				:show-overflow-tooltip="true" :row-class-name="tableRowClassName"
				@selection-change="handleSelectionChange" border>
				<el-table-column v-if="['act_add'].includes(dialogStatus)" type="selection" width="55" align="center" />
				<el-table-column type="index" width="55" align="center" label="序号" />
				<el-table-column label="出库仓位" align="center" width="200px" prop="position.name"></el-table-column>
				<el-table-column label="图片" width="60" align="center" prop="goods_info.image">
					<template #default="scope">
						<el-image style="width: 35px; height: 35px" :src="scope.row.goods_info.image" :zoom-rate="1.2"
							:max-scale="7" :min-scale="0.2" :preview-src-list="[scope.row.goods_info.image]"
							:initial-index="0" fit="cover" />
					</template>
				</el-table-column>
				<el-table-column label="名称" align="center" prop="goods_info.name" min-width="150"></el-table-column>
				<el-table-column label="编码" align="center" prop="goods_info.sku" min-width="150" />
				<el-table-column label="物料号" align="center" prop="goods_info.part_no" min-width="150"></el-table-column>
				<el-table-column label="品牌" align="center" prop="goods_info.brand" min-width="150" />
				<el-table-column label="规格型号" align="center" prop="goods_info.specs" min-width="150" />
				<el-table-column label="单位" align="center" prop="goods_info.unit" min-width="80" />
				<el-table-column label="备注" align="center" prop="goods_info.mark" min-width="200"></el-table-column>				
				<el-table-column  v-if="['act_add'].includes(dialogStatus)" label="现有库存" fixed="right"  align="center" width="150px"
					prop="num"></el-table-column>
				<el-table-column label="出库数量"  v-if="['act_add'].includes(dialogStatus)" fixed="right" align="center" width="150px" prop="snum">
					<template #default="scope">
						<el-input-number style="width: 100%;"  :min="0" :max="scope.row.num"
							v-model="scope.row.snum" />
					</template>
				</el-table-column>
				<el-table-column label="出库数量"  v-if="['act_info'].includes(dialogStatus)" fixed="right" align="center" width="150px" prop="num">
				</el-table-column>
			</el-table>
		</el-card>
		<!-- 选择出库物品 -->
		<selectShopOut  ref="selectShopOutRef"  @getSelectItems="getSelectItems"></selectShopOut>
		

	</el-drawer>
</template>
<script setup lang="ts">
	defineOptions({
		name: "Stockroom",
		inheritAttrs: false,
	});

	import selectShopOut from '../selectShop/out.vue'

	//接口地址
	import {
		getPositionOptions,
		getOutbound,
		getStockroomSelectList,
		getOutboundAdd
	} from "@/api/wms";

	import { useUserStore } from "@/store/modules/user";
	import { useBaseConfigStore } from "@/store/modules/baseConfig";
	const baseConfigStore = useBaseConfigStore();
	const useStore = useUserStore();
	const emit = defineEmits(['initRefreshList']);
	const formTempDataStatic = {
		cid: "",//公司id
		sid: "",//仓库id
		batch_no: "",//批单号
		outbound_time: "",//入库时间
		mark: "",//备注
		goods: []//商品列表
	}
	// 验证规则
	const cRules = {
		cid: [{ required: true, message: '请选择所属公司', trigger: 'change' }],
		sid: [{ required: true, message: '请选择所属仓库', trigger: 'change' }],
		outbound_time: [{ required: true, message: '请选择出库时间', trigger: 'change' }],
	}

	const props = defineProps<{
		infoChild : any;
	}>();
	const selectShopOutRef = ref();
	const dataFormRef = ref(ElForm)


	const dataTableRef = ref();
	const loading = ref(false);
	const stockList = ref<any>();
	const positionList = ref<any>()//仓位列表

	const formTemp = ref<any>(JSON.parse(JSON.stringify(formTempDataStatic)))
	const dialogVisible = ref(false);
	const dialogStatus = ref<string>(""); // 操作行为 formText
	const formText = ref<string>(""); // 操作窗口标题
	const multipleSelection = ref<any>([]);
	const parentsData = ref<any>();//父级传来的参数
	const dialogAdd = reactive<DialogOption>({
		visible: false,
	});
	const isDisabled = ref(false)


	// 数据多选事件
	function handleSelectionChange(val : any) {
		multipleSelection.value = val
	}
	// 操作按钮样式
	function buttonType(val : number) {
		if (val === 1) {
			return 'primary'
		} else {
			return 'info'
		}
	}
	// 监听用户选择的那个仓库
	watch(() => formTemp.value.sid, (newValue, oldValue) => {
		getPositionList(newValue)
	})
	//新增或者修改加载load按钮
	function handleShow(row : any, act : string) {
		parentsData.value = row;
		handleDo(row, act)
	}

	// 操作
	function handleDo(row : any, act : string) {
		dialogStatus.value = act
		switch (act) {
			case 'act_add':
			
				dialogVisible.value = true;
				formText.value = '新建出库单'
				formTemp.value = JSON.parse(JSON.stringify(formTempDataStatic))
				nextTick(() => {
					setTimeout(() => { dataFormRef.value.clearValidate(); }, 100)
				})
				break
			case 'act_info':
				dialogVisible.value = true;
				formText.value = '查看出库单详情'
				loading.value = true;
				initStockList(row.cid);
				getOutbound({ id: row.id }).then((res) => {
					formTemp.value = res.data
					formTemp.value.goods = res.data.detail;
					loading.value = false;
				}).finally(() => { })

				break
			case 'act_del':
				handleDelete(JSON.parse(JSON.stringify(row)))
				break
			default:

		}
	}
	// 添加物品
	function handleAdd() {
		if (formTemp.value.sid == "") {
			ElMessage({
				message: '请先选择仓库！！',
				type: 'error',
			})
			return false;
		}
		// dialogAdd.visible = true;
		selectShopOutRef.value.handleShow(formTemp.value, "act_add")
	}


	// 选择公司id
	function nodeClickCompany(a : any, b : any, c : any, d : any) {
		formTemp.value.sid = "";
		initStockList(a.cid)
	}
	// 取消选择公司id
	function nodeClearCompany() {
		stockList.value = [];
		formTemp.value.sid = "";
	}
	/**获取仓库列表 */
	function initStockList(cid ?: number) {
		getStockroomSelectList({ cid: cid }).then((res) => {
			stockList.value = res.data;
		}).finally(() => { })
	}
	// 获取仓位
	function getPositionList(sid ?: any) {
		getPositionOptions({
			sid: sid
		}).then((res) => {
			console.log(res)
			positionList.value = res.data;
		}).finally(() => { })
	}











	/**获取仓库列表 */
	// function initStockList() {
	// 	getStockroomOptions({}).then((res) => {
	// 		console.log(res)
	// 		stockList.value = res.data;
	// 	}).finally(() => {

	// 	})
	// }
	function tableRowClassName(row : any) {
		row.row.index = row.rowIndex;
	}
	function handleSubmit() {
		
		const unForm = JSON.parse(JSON.stringify(formTemp.value))
		var failData = unForm.goods.reduce((accumulator, item, index) => {
			if (item.num == 0) {
				accumulator.push(`${item.name}的出库数量需要大于零。`);
			}
			return accumulator;
		}, []);
		if (failData.length > 0) {
			ElMessage({
				message: failData.join(' '),
				type: 'error',
			})
			return false;
		}
		var newsGood = unForm.goods.map((item, index) => {
			return {
				goods_id: item.id,
				position: item.position.id,
				num: item.snum
			}
		})
		successBack({
			sid: unForm.sid,
			batch_no: unForm.batch_no,
			outbound_time: unForm.outbound_time,
			mark: unForm.mark,
			goods: newsGood,
			applicant_id: useStore.userId
		})
	}

	function successBack(payload : any) {
		getOutboundAdd(payload).then((res) => {
			ElMessage({
				message: res.msg,
				type: 'success'
			})
			emit('initRefreshList');
			dialogVisible.value = false;
		
		}).finally(() => { })
	}



	function handleDelete(Id ?: number) {
		const Ids = multipleSelection.value.map((item : any) => item.index)
		if (!Ids) {
			ElMessage.warning("请勾选删除项");
			return;
		}
		ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
			confirmButtonText: "确定",
			cancelButtonText: "取消",
			type: "warning",
		}).then(() => {
			// loading.value = true;
			// 使用 filter 方法过滤掉 b 数组中索引在 a 数组中的项
			formTemp.value.goods = formTemp.value.goods.filter(item => !Ids.includes(item.index));
		}, function () {
			console.log('取消删除')
		});


	}

	function getSelectItems(el : any) {
		//  去重合并操作
		const newArray = el.map(item => {
			return {
				...item,
				goods_info: item,
				position: {
					id: item.pid,
					name: item.position
				},
				snum: 0
			};
		});

		var newsArr = fliterData(formTemp.value.goods, newArray)
		formTemp.value.goods = [...formTemp.value.goods, ...newsArr];
		dialogAdd.visible = false;
	}
	function fliterData(value1, value2) {
		var news = []

		for (var i = 0; i < value2.length; i++) {
			var itemA = value2[i];
			var isTrue = value1.some(itemB =>
				itemB.goods_info.id === itemA.goods_info.id &&
				itemB.position.id === itemA.position.id &&
				itemB.goods_info.name === itemA.goods_info.name &&
				itemB.goods_info.brand === itemA.goods_info.brand)

			if (!isTrue) {
				news.push(itemA)
			}
		}
		return news
	}





	defineExpose({
		handleShow
	});

	onMounted(() => {

	})
</script>


<style scoped>
	.avatar-uploader .avatar {
		width: 178px;
		height: 178px;
		display: block;
	}

	.min220 {
		width: 220px
	}
</style>